package com.schoolhelper.controller.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMUserInfo;
import com.hyphenate.chat.adapter.EMACallback;
import com.longsh.optionframelibrary.OptionBottomDialog;
import com.schoolhelper.model.Model;
import com.schoolhelper.model.YyzExecutors;
import com.schoolhelper.model.dao.jsonparse.LwlControllerJsonParser;
import com.schoolhelper.model.dao.jsonparse.LwlJsonParser;
import com.schoolhelper.model.dao.okhttp.LwlRequestUrl;
import com.schoolhelper.model.dao.okhttp.RefactorRequestUrl;
import com.schoolhelper.model.dao.okhttp.RequestUtil;
import com.schoolhelper.model.entity.Order;
import com.schoolhelper.model.entity.OrderImage;
import com.schoolhelper.model.entity.User;
import com.schoolhelper.model.vo.TokenVo;
import com.schoolhelper.utils.ImageUtils;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.constant.Api;
import com.schoolhelper.utils.constant.LwlApi;
import com.schoolhelper.utils.constant.MessageConstant;
import com.schoolhelper.utils.constant.ZyyApi;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import lombok.SneakyThrows;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private String[] settings;
    LinearLayout ll_return;
    ListView listView;
    String userId;


    //拍照功能参数
    private static final int TAKE_PHOTO = 1;
    private static final int CHOOSE_PHOTO = 2;
    private final static int CROP_IMAGE = 3;
    //imageUri照片真实路径
    private Uri imageUri;
    //照片存储
    private File filePath;
    private Bitmap bitmap;

    private int imageWidth;
    private int imageHeight;
    private List<String> getImageMethod = new ArrayList<String>();
    private LwlJsonParser lwlJsonParser;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        init();

    }

    public void init() {
        listView = (ListView) findViewById(R.id.list_view);
        ll_return = findViewById(R.id.ll_return);

        lwlJsonParser = new LwlControllerJsonParser();
        userId = MyCache.read(getApplicationContext(), "userId");
        System.out.println("token_info:" + userId);

        if (userId != null) {
            settings = new String[]{"修改昵称", "修改签名", "修改头像", "退出登录"};
//            settings = new String[]{"登录"};
        } else {
            settings = new String[]{"登录"};
        }


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SettingActivity.this,
                android.R.layout.simple_list_item_1, settings);
        listView.setAdapter(adapter);

        ll_return.setOnClickListener(this);
        listView.setOnItemClickListener(this);

        getImageMethod.add("拍照");
        getImageMethod.add("从相册选择");

    }

    @Override
    public void onClick(View view) {
        if (view == ll_return) {
            finish();
////            this.finish();
//            Intent intent = new Intent();
//            intent.setClass(SettingActivity.this, AccountActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        if (position == 0) {
            if (settings.length == 4) {
                //修改昵称
                EditText input = new EditText(this);
                Toast.makeText(SettingActivity.this, "修改昵称", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("修改昵称").setView(input);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @SneakyThrows
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String username = input.getText().toString().trim();
                        Toast.makeText(SettingActivity.this, username, Toast.LENGTH_SHORT).show();
                        //......
                        // 查询User
                        HashMap<Object, Object> usernameParam = new HashMap<>();
                        usernameParam.put("username", username);

                        Future<String> future = YyzExecutors.submit(new Callable<String>() {
                            @Override
                            public String call() throws Exception {

                                return RefactorRequestUrl.getPostResponseJson(Api.BASE_URL, "/user/getByUsername",
                                        new HashMap<>(), usernameParam);
                            }
                        });

                        String res = future.get();
                        System.out.println(res);
                        String userInfo = MyCache.read(getApplicationContext(), "userInfo");
                        JSONObject jsonObject = (JSONObject) JSONObject.parse(userInfo);
                        User user = JSON.parseObject(String.valueOf(jsonObject), User.class);
                        System.out.println("修改前username: " + user.getUsername());
                        System.out.println("修改后username: " + username);
                        user.setUsername(username);
                        Future<Boolean> future2 = YyzExecutors.submit(new Callable<Boolean>() {
                            @Override
                            public Boolean call() throws Exception {
                                return RequestUtil.put(Api.BASE_URL, Api.USER, user);
                            }
                        });

                        boolean put = future2.get();
                        if (put) {
                            System.out.println("修改成功");
                            Toast.makeText(SettingActivity.this, username + put, Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setClass(SettingActivity.this, AccountActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);

                        } else {
                            System.out.println("修改失败");
                            Toast.makeText(SettingActivity.this, username + put, Toast.LENGTH_SHORT).show();

                        }

                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
            } else {
                Toast.makeText(SettingActivity.this, "登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setClass(SettingActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        } else if (position == 1) {
            Toast.makeText(SettingActivity.this, "修改签名", Toast.LENGTH_SHORT).show();
        } else if (position == 2) {
            Toast.makeText(SettingActivity.this, "修改头像", Toast.LENGTH_SHORT).show();
            selectImage();

        } else if (position == 3) {
            //退出登录
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("确认退出？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String token_info = MyCache.read(getApplicationContext(), "token");
                    TokenVo tokenVo = new TokenVo(token_info);
                    String postResponseJson = RefactorRequestUrl.getPostResponseJson(Api.BASE_URL, ZyyApi.LOGIN_QUIT_API, new HashMap<>(), tokenVo);
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(postResponseJson);
                    if (Objects.equals(jsonObject.get("code"), 200)) {
                        // 退出登录环信
                        EMClient.getInstance().logout(true, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                MyCache.write(getApplicationContext(), "token", null);
                                MyCache.write(getApplicationContext(), "userId", null);
                                runOnUiThread(() -> {
                                    Toast.makeText(SettingActivity.this, postResponseJson, Toast.LENGTH_SHORT).show();
                                });
                                Intent intent = new Intent();
                                intent.setClass(SettingActivity.this, AccountActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }

                            @Override
                            public void onError(int code, String error) {
                                runOnUiThread(() -> {
                                    Toast.makeText(getApplicationContext(), "退出登录失败: " + error, Toast.LENGTH_SHORT).show();
                                });
                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }
                        });

                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });

            builder.show();
        }
    }

    /**
     * 提交图片
     */
    private void postImage() {
        Model.getInstance().getGlobalSingleThreadPool().execute(() -> {
            if (filePath != null) {

                String image1Url = postImageToSmms(filePath);
                System.out.println("image1Url: " + image1Url);
                if (image1Url.equals(MessageConstant.FAIL_MSG)) {
                    runOnUiThread(() -> {
                        Toast.makeText(getApplicationContext(), "您上传的图片过大，请剪切后再上传", Toast.LENGTH_SHORT).show();
                    });
                }
                MyCache.write(getApplicationContext(), image1Url, ImageUtils.bitmap2String(bitmap, 50));
                if (!postImageToUserImg(userId, image1Url)) {
                    System.out.println("修改头像时上传到数据库失败");
                }
                System.out.println("图片上传成功");
                Intent intent = new Intent();
                intent.putExtra("imgUrl", image1Url);
                SettingActivity.this.setResult(1, intent);
                SettingActivity.this.finish();
            }
        });

    }

    private boolean postImageToUserImg(String userId, String imageUrl) {
        Map<String, String> headers = new HashMap<>();
//        OrderImage orderImage = new OrderImage(null, userId, imageUrl);
//        Model.getInstance().getGlobalSingleThreadPool().execute(() -> {
        User byId = RequestUtil.getById(Api.USER, Long.parseLong(userId), User.class);
        byId.setProfileImg(imageUrl);
        boolean put = RequestUtil.put(Api.USER, byId);
//        });
        return put;
    }

    /**
     * 把图像上传到图床，参数是File类对象，返回结果是图像的url
     *
     * @param image
     * @return
     */
    private String postImageToSmms(File image) {
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36");
        headers.put("Authorization", "mc1bMY0iL1hW9N478FWQ0AZ3B11TqBw9");
        return LwlRequestUrl.postSmmsThenGetUrl(LwlApi.BSER_SMMSURL, LwlApi.SMMS_UPLOAD, headers, image, lwlJsonParser);
    }

//    private boolean postOrder() {
//        Order order = new Order(null,
//                userId,
//                postEtTitle.getText().toString(),
//                category,
//                postEtDescription.getText().toString(),
//                Integer.parseInt(postEtMoney.getText().toString()),
//                "0",
//                null,
//                new Date(),
//                null,
//                null);
//
//        boolean postOrderResult = RefactorRequestUrl.justPost(Api.BASE_URL, Api.ORDER, new HashMap<>(), order, lwlJsonParser);
//        if (postOrderResult) {
//            return true;
//        } else {
//            Toast.makeText(PostActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
//            return false;
//        }
//    }
//
//    private boolean check() {
//        if (Integer.parseInt(postEtMoney.getText().toString()) < 1) {
//            Toast.makeText(PostActivity.this, "跑腿费至少是1元及以上哦", Toast.LENGTH_SHORT).show();
//            return false;
//        } else if (postEtTitle.getText().toString().equals("")) {
//            Toast.makeText(PostActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
//            return false;
//        } else if (postEtDescription.getText().toString().equals("")) {
//            Toast.makeText(PostActivity.this, "介绍不能为空", Toast.LENGTH_SHORT).show();
//            return false;
//        } else if (category.equals("无")) {
//            Toast.makeText(PostActivity.this, "分类不能为空", Toast.LENGTH_SHORT).show();
//            return false;
//        }
//        return true;
//    }

    //获取图片，即可拍照，也可以本地上传
    private void selectImage() {
        final OptionBottomDialog optionBottomDialog = new OptionBottomDialog(SettingActivity.this, getImageMethod);
        optionBottomDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // optionBottomDialog.dismiss();
                switch (position) {
                    case 0:
                        //启动相机程序
                        //隐式Intent
                        Intent intent_photo = new Intent("android.media.action.IMAGE_CAPTURE");
                        //putExtra()指定图片的输出地址，填入之前获得的Uri对象
                        imageUri = ImageUtils.getImageUri(SettingActivity.this);
                        intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //startActivity( intent_photo );
                        startActivityForResult(intent_photo, TAKE_PHOTO);
                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    case 1:
                        //打开相册
                        openAlbum();
                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //打开相册
    private void openAlbum() {
        Intent intent_album = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(intent_album, CHOOSE_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //需要对拍摄的照片进行处理编辑
                    //拍照成功的话，就调用BitmapFactory的decodeStream()方法把图片解析成Bitmap对象，然后显示
                    Log.i("Test", "onActivityResult TakePhoto : " + imageUri);
                    //Bitmap bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //takephoto.setImageBitmap( bitmap );
                    //设置照片存储文件及剪切图片
                    File saveFile = ImageUtils.getTempFile();
                    filePath = ImageUtils.getTempFile();
                    startImageCrop(saveFile, imageUri);
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //选中相册照片显示
                    Log.i("Test", "onActivityResult: 执行到打开相册了");
                    try {
                        imageUri = data.getData(); //获取系统返回的照片的Uri
                        Log.i("Test", "onActivityResult: uriImage is " + imageUri);
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(imageUri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //                        photo_taken.setImageBitmap(bitmap);
                        //设置照片存储文件及剪切图片
                        File saveFile = ImageUtils.setTempFile(SettingActivity.this);
                        filePath = ImageUtils.getTempFile();
                        startImageCrop(saveFile, imageUri);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CROP_IMAGE:
                if (resultCode == RESULT_OK) {
                    Log.i("Test", "onActivityResult: CROP_IMAGE" + "进入了CROP");
                    // 通过图片URI拿到剪切图片
                    //bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //通过FileName拿到图片
                    bitmap = BitmapFactory.decodeFile(filePath.toString());
                    postImage();
                    runOnUiThread(() -> {
                        Toast.makeText(getApplicationContext(), "跳转中...", Toast.LENGTH_LONG).show();
                    });
//                    if (postImage()){
//                        Toast.makeText(SettingActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
//                    }else {
//                        Toast.makeText(SettingActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
//                    }

                    //把裁剪后的图片展示出来
//                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) postIvDescription.getLayoutParams();
//                    params.height = imageHeight;
//                    params.width = imageWidth;
//                    params.setMargins(20, 30, 0, 0);
//                    if (imageId == 1) {
//                        System.out.println("填充第一个图片");
//                        postIvDescription1.setLayoutParams(params);
//                        postIvDescription1.setImageBitmap(bitmap);
//                        image1 = filePath;
//                    } else if (imageId == 2) {
//                        System.out.println("填充第二个图片");
//                        postIvDescription2.setLayoutParams(params);
//                        postIvDescription2.setImageBitmap(bitmap);
//                        image2 = filePath;
//                    } else if (imageId == 3) {
//                        System.out.println("填充第三个图片");
//                        postIvDescription.setImageBitmap(bitmap);
//                        image3 = filePath;
//                    }
//                    postIvDescription.setImageBitmap( bitmap );
                    //ImageUtils.Compress( bitmap );
                }
                break;
            default:
                break;
        }
    }

    //剪切图片
    private void startImageCrop(File saveToFile, Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        Log.i("Test", "startImageCrop: " + "执行到压缩图片了" + "uri is " + uri);
        intent.setDataAndType(uri, "image/*");//设置Uri及类型
        //uri权限，如果不加的话，   会产生无法加载图片的问题
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("crop", "true");//
        intent.putExtra("aspectX", 1);//X方向上的比例
        intent.putExtra("aspectY", 1);//Y方向上的比例
        intent.putExtra("outputX", imageHeight);//裁剪区的X方向宽
        intent.putExtra("outputY", imageWidth);//裁剪区的Y方向宽
        intent.putExtra("scale", true);//是否保留比例
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("return-data", false);//是否将数据保留在Bitmap中返回dataParcelable相应的Bitmap数据，防止造成OOM，置位false

        //判断文件是否存在
        //File saveToFile = ImageUtils.getTempFile();
        if (!saveToFile.getParentFile().exists()) {
            saveToFile.getParentFile().mkdirs();
        }
        //将剪切后的图片存储到此文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveToFile));
        Log.i("Test", "startImageCrop: " + "即将跳到剪切图片");
        startActivityForResult(intent, CROP_IMAGE);
    }

}
